package com.easylinkin.linkappapi.penetsecuremanage.controller;


import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.config.entity.SysDictItem;
import com.easylinkin.linkappapi.config.service.SysDictItemService;
import com.easylinkin.linkappapi.penetsecuremanage.dto.RailLinkappGridManagementInfoDTO;
import com.easylinkin.linkappapi.penetsecuremanage.entity.RailLinkappGridManagementInfo;
import com.easylinkin.linkappapi.penetsecuremanage.mapper.RailLinkappGridManagementInfoMapper;
import com.easylinkin.linkappapi.penetsecuremanage.service.IRailLinkappGridManagementInfoService;
import com.easylinkin.linkappapi.penetsecuremanage.utils.ExcelHelper;
import com.easylinkin.linkappapi.penetsecuremanage.utils.GridInfo;
import com.easylinkin.linkappapi.penetsecuremanage.vo.OrgaStructureChartVO;
import com.easylinkin.linkappapi.penetsecuremanage.vo.RailLinkappGridManagementInfoVO;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**后台穿透式安全管理/网格信息接口类
 * @author lyk
 * @date 2025/6/20 下午 2:29
 */
@RestController
@RequestMapping("/gridManagementInfo")
public class RailLinkappGridManagementInfoController {
    @Autowired
    private IRailLinkappGridManagementInfoService railLinkappGridManagementInfoService;

    @Autowired
    private SysDictItemService dictItemService;
    @Autowired
    private LinkappUserContextProducer linkappUserContextProducer;

    @Autowired
    private RailLinkappGridManagementInfoMapper railLinkappGridManagementInfoMapper;
    /**
     * 列表分页查询
     * @param requestModel
     * @return
     */
    @PostMapping(value = "/getPage")
    public RestMessage selectPage(@RequestBody RequestModel<RailLinkappGridManagementInfoDTO> requestModel) {
        Assert.notNull(requestModel.getPage(), "page 不能为空");
        IPage<RailLinkappGridManagementInfoVO> record = railLinkappGridManagementInfoService.selectPage(requestModel.getPage(), requestModel.getCustomQueryParams());
        return RestBuilders.successBuilder(record).build();
    }
    /**
     * 列表查询全部记录
     * @param dto
     * @return
     */
    @PostMapping(value = "/list")
    public RestMessage selectPage(@RequestBody RailLinkappGridManagementInfoDTO dto) {
      List<RailLinkappGridManagementInfoVO> record  = railLinkappGridManagementInfoService.getList(dto);
      return RestBuilders.successBuilder(record).build();
    }

    /** 网格信息批量新增接口
     * @param dto
     * {
     *  addList://新增需要传入数组
     * }
     * @return
     * err:
     */
    @PostMapping(value = "/save")
    public RestMessage save(@RequestBody RailLinkappGridManagementInfoDTO dto){
      if (Objects.isNull(dto.getAddList())){
          return RestBuilders.failureMessage().setMessage("新增参数不能为空");
      }
      if (dto.getAddList().size() == 0){
          return RestBuilders.failureMessage().setMessage("新增内容不能为空");
      }
      List<String> result = railLinkappGridManagementInfoService.saveList(dto);
      if (result.size() > 0){
          return RestBuilders.failureMessage().setMessage("操作失败:"+String.join(",",result));
      }else{
          return RestBuilders.successBuilder("操作成功").build();
      }
    }
    @GetMapping(value = "/export")
    public void export(HttpServletRequest request, HttpServletResponse response){
        RailLinkappGridManagementInfoDTO dto = new RailLinkappGridManagementInfoDTO();
        dto.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        List<RailLinkappGridManagementInfoVO> record  = railLinkappGridManagementInfoService.getList(dto);
        List<GridInfo> result = new ArrayList<>();
        for (RailLinkappGridManagementInfoVO vo:record){
            //获取字典
            GridInfo map = new GridInfo();
            map.setNumber(vo.getNumber());
            map.setGridType(vo.getGridType());

            if (StringUtils.isEmpty(vo.getEngineeType())){
                map.setEngineeType("");
            }else{
                //字典
                SysDictItem enginee_type = dictItemService.selectByDictItem("enginee_type", vo.getEngineeType());
                if (Objects.isNull(enginee_type)){
                    map.setEngineeType("");
                }else {
                    map.setEngineeType(enginee_type.getItemText());
                }
            }
            map.setGridName(vo.getGridName());
            map.setMileageRange(vo.getMileageRange());
            //安监专务
            if (StringUtils.isEmpty(vo.getSafetySupName())){
                map.setSafetySupName("");
            }else{
                map.setSafetySupName(vo.getSafetySupName()+"   "+(StringUtils.isEmpty(vo.getSafetySupPhone())?"":vo.getSafetySupPhone()));
            }
            //网格安全员
            map.setGridSecName(vo.getGridSecName());
            map.setGridSecPhone(vo.getGridSecPhone());

            //施工员/领工员
            map.setGridForemanName(vo.getGridForemanName());
            map.setGridForemanPhone(vo.getGridForemanPhone());
            //现场负责人/安全员
            map.setGridSitemanName(vo.getGridSitemanName());
            map.setGridSitemanPhone(vo.getGridSitemanPhone());

            map.setConstructionTeam(vo.getConstructionTeam());
            map.setStaffNumber(vo.getStaffNumber());
            map.setIsFormalEmployee(vo.getIsFormalEmployee());
            map.setIsSoleDuty(vo.getIsSoleDuty());
            map.setHoldCert(vo.getHoldCert());
            map.setNotes(vo.getNotes());
            result.add(map);
        }

        ExcelHelper.exportGridInfoToExcel(result,"网格信息.xls",request,response);
    }

    /**
     * 网格信息删除接口
     * @param ids
     * @return
     */
    @GetMapping(value = "/del")
    public RestMessage del(String ids){
        if (StringUtils.isEmpty(ids)){
            return RestBuilders.failureMessage("网格id不能为空");
        }
        String[] split = ids.split(",");
        for (String id:split){
            if (!StringUtils.isEmpty(id)){
                railLinkappGridManagementInfoService.removeById(Long.valueOf(id));
            }
        }
        return RestBuilders.successBuilder("操作成功").build();
    }

    /**网格信息编辑
     * @param dto
     * {"id":必填}
     * @return
     */
    @PostMapping(value = "/edit")
    public RestMessage edit(@RequestBody RailLinkappGridManagementInfoDTO dto){
        if (Objects.isNull(dto.getId())){
            return RestBuilders.failureMessage().setMessage("网格id不能为空");
        }
        RailLinkappGridManagementInfo byId = railLinkappGridManagementInfoService.getById(dto.getId());
        if (Objects.isNull(byId)){
            return RestBuilders.failureMessage("记录不存在");
        }
        railLinkappGridManagementInfoService.edit(dto);
        return RestBuilders.successBuilder("操作成功").build();
    }

    /**
     * 项目监督组织架构图数据获取接口
     * @return
     */
    @GetMapping(value = "/supervisoryOrgStructureChart")
    public RestMessage supervisoryOrgStructureChart(){
        OrgaStructureChartVO orgaStructureChartVO = railLinkappGridManagementInfoService.supervisoryOrgaStructureChart();
        return RestBuilders.successBuilder(orgaStructureChartVO).build();
    }

    /**
     * @param dto
     * {
     *     addList:[{
     *         "id":"",
     *         "gridMeetId":""//紧急联系人id
     *         "announcementFileUrl":""// 公示牌文件url
     *     }]
     * }
     * @return
     */
    @PostMapping(value = "/addMeetAndAnnouncement")
    public RestMessage addMeetAndAnnouncement(@RequestBody RailLinkappGridManagementInfoDTO dto){
        if (dto.getAddList().size() == 0){
            return RestBuilders.failureMessage("请填写表单");
        }
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        //id校验
        List<RailLinkappGridManagementInfoDTO> addList = dto.getAddList();
        for (RailLinkappGridManagementInfoDTO grid:addList){
            if (Objects.isNull(grid.getId())){
                return RestBuilders.failureMessage("id不能为空");
            }
            //判断是否担任其他职务
            if (StringUtils.isNotEmpty(grid.getGridMeetId())){
                Integer integer = railLinkappGridManagementInfoMapper.checkAjzwByNumber(tenantId, grid.getGridMeetId());
                if (integer>0){
                    return RestBuilders.failureMessage("当前人员已经担任安监专务！");
                }
                Integer integer1 = railLinkappGridManagementInfoMapper.checkOtherByNumber(tenantId, grid.getGridMeetId());
               if (integer1>0){
                   return RestBuilders.failureMessage("当前人员已经担任了其他职务！");
               }
            }
        }
        //保存
        railLinkappGridManagementInfoService.addMeetAndAnnouncement(addList);
        return RestBuilders.successBuilder("操作成功").build();
    }

}